function varargout = Spin2Win(varargin)
% SPIN2WIN M-file for Spin2Win.fig
%      SPIN2WIN, by itself, creates a new SPIN2WIN or raises the existing
%      singleton*.
%      
%      H = SPIN2WIN returns the handle to a new SPIN2WIN or the handle to
%      the existing singleton*.
%
%      SPIN2WIN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SPIN2WIN.M with the given input arguments.
%
%      SPIN2WIN('Property','Value',...) creates a new SPIN2WIN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Spin2Win_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Spin2Win_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Spin2Win

% Last Modified by GUIDE v2.5 30-Nov-2013 10:12:07

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Spin2Win_OpeningFcn, ...
                   'gui_OutputFcn',  @Spin2Win_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

%-----------------------------------------------------------------------
% --- Executes just before Spin2Win is made visible.
function Spin2Win_OpeningFcn(hObject, eventdata, handles, varargin)

% Choose default command line output for Spin2Win
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% Fill tables with zeros and ones
tmp = ones(5,1);
set(handles.uitable2 , 'data' , tmp);
tmp = zeros(9,9);
set(handles.uitable1 , 'data' , tmp);

%Copy filled table data to variables
handles.calc_settings = get(handles.uitable2 , 'data');
handles.geom_data     = get(handles.uitable1 , 'data');

% Set checkbox5 to 1 so that plot is generated by default
set(handles.checkbox5,'Value',1)

% Update handles and object
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Outputs from this function are returned to the command line.
function varargout = Spin2Win_OutputFcn(hObject, eventdata, handles)

% Get default command line output from handles structure
varargout{1} = handles.output;

%-----------------------------------------------------------------------
% --- Executes on button press in pushbutton1
% Run Calculation button
function pushbutton1_Callback(hObject, eventdata, handles)

% Disable button when pressed/working and change button text.
% set(handles.pushbutton1, 'Enable' , 'off')
set(handles.pushbutton1, 'String' , 'WORKING...')
pause(0.1);

%Import and merge data to send
% using merge_indata function
senddat = merge_indata(handles.geom_data, handles.calc_settings);

%Get figure number from settings and prefix from GUI
fignr = handles.calc_settings(5);
prefix = get(handles.edit2,'String');

%Send data to Main_calc for prossesing.
[mout] = Main_calc(senddat,prefix);

% Save output data if needed by other functions
save mout

% Check if plots are to be generated or not
if get(handles.checkbox5,'Value') == 1
Plotter(mout.Ten_c, mout.Ten_r, mout.intf, mout.r_mark, mout.r_mark2, ...
        mout.r, mout.ri, fignr, mout.stamp, prefix)
end

% Increase plot nr if that checkbox is set
handles.calc_settings(5) = fignr + get(handles.checkbox2 , 'Value');
set(handles.uitable2 , 'data' , handles.calc_settings);

% Enable button done and restore button text.
set(handles.pushbutton1, 'Enable' , 'on')
set(handles.pushbutton1, 'String' , 'Run Calculation')

%Update values, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes on button press in pushbutton2. 
% Load Default Isometric data button
function pushbutton2_Callback(hObject, eventdata, handles)

% Load data into tmp using split_indata function
[tmp1, tmp2] = split_indata(load_default_iso);

% Format imported data to correct format and make sure all values are
% valid.
tmp3 = ones(5,1);
tmp3(1) = floor(tmp2(5));
tmp3(2) = tmp2(2);
tmp3(3) = tmp2(3);
tmp3(4) = tmp2(4);
tmp3(5) = floor(handles.calc_settings(5));

% Copy imported and formatted data to tables
set(handles.uitable2 , 'data' , tmp3);
set(handles.uitable1 , 'data' , tmp1);

%Copy table data to variables
handles.calc_settings = get(handles.uitable2 , 'data');
handles.geom_data     = get(handles.uitable1 , 'data');

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes on button press in pushbutton3.
% Load Default Orthotropic data button
function pushbutton3_Callback(hObject, eventdata, handles)

% Load data into tmp using split_indata function
[tmp1, tmp2] = split_indata(load_default_ort);

% Format imported data to correct format and make sure all values are
% valid.
tmp3 = ones(5,1);
tmp3(1) = tmp2(5);
tmp3(2) = tmp2(2);
tmp3(3) = tmp2(3);
tmp3(4) = tmp2(4);
tmp3(5) = handles.calc_settings(5);

% Copy data to tables
set(handles.uitable2 , 'data' , tmp3);
set(handles.uitable1 , 'data' , tmp1);

%Copy table data to variables
handles.calc_settings = get(handles.uitable2 , 'data');
handles.geom_data     = get(handles.uitable1 , 'data');

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes on button press in checkbox1. 
% Shell number ovveride checkbox
function checkbox1_Callback(hObject, eventdata, handles)

% Update checkbox status.

%-----------------------------------------------------------------------
% --- Executes on button press in checkbox2. 
% Increase plot number after each run checkbox
function checkbox2_Callback(hObject, eventdata, handles)

% Update checkbox status.

%-----------------------------------------------------------------------
% --- Executes when entered data in editable cell(s) in uitable2. 
% Settings table updater, updates on change in  settings table.
function uitable2_CellEditCallback(hObject, eventdata, handles)

% Check for shell number <=9 and  compare to checkbox status
tmp = get(handles.uitable2 , 'data');
if get(handles.checkbox1,'Value') == 0
    tmp(1) = min(tmp(1),9);
end

% make sure input is within allowed values
tmp(5) = floor(max(tmp(5),1));
tmp(4) = max(tmp(4),0);
tmp(3) = max(tmp(3),0);
tmp(2) = max(tmp(2),0);
tmp(1) = floor(max(tmp(1),1));

% If the new number of shells is longer than the current maximal
% number: expand the table and fill the new columns with zeros
% but keep current data in cells.
if length(handles.geom_data(1,:)) < tmp(1)
    tmp2 = zeros(8,tmp(1));
    tmp3 = get(handles.uitable1 , 'data');
    for i = 1:1:8
        for k = 1:1:tmp(1)     
        if k <= length(tmp3(1,:))   
            tmp2(i,k) = tmp3(i,k);
        end     
        end
    end  
    set(handles.uitable1 , 'data' , tmp2); 
end

% Copy new values to global handles and table
handles.calc_settings = tmp;
set(handles.uitable2 , 'data' , tmp);
handles.geom_data = get(handles.uitable1 , 'data');

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes when entered data in editable cell(s) in uitable1. 
% Geometry table updater, updates on change in geometry table.
function uitable1_CellEditCallback(hObject, eventdata, handles)

%Copy table data to variables, make sure they are positive and real
% by using abs command
handles.geom_data     = abs(get(handles.uitable1 , 'data'));

%Send positive data back to table
set(handles.uitable1 , 'data', handles.geom_data)

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes on button press in pushbutton6. 
% Load File button
function pushbutton6_Callback(hObject, eventdata, handles)

% Load file using built in uigetfile popup window and ReadFile subroutine
% Filename must contain Spin2Win_ and be a .txt-file
[filedata, hdlines] = ReadFile(uigetfile('Spin2Win_*.txt', ...
      'Choose an old output-file, must begin with Spin2Win_'));

% If load of file sucseeds copy file data into correct variables
% If load fails do nothing
if ~isnumeric(filedata)
handles.filedata = filedata;
handles.hdlines = hdlines;

% Reset listbox2, run list, selected selected value to 1
handles.importnr = 1;
set(handles.listbox2,'Value',1)

% Update listbox2 with found hdlines remove 'Date and time of run:'
for i=1:1:length(hdlines)
    strtmp(i,1) = strrep(filedata(hdlines(i)),'Date and time of run: ','');
end
set(handles.listbox2,'String',strtmp)
% Enable load list data button
set(handles.pushbutton7,'Enable','on')
end

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes on selection change in listbox2. 
% Loaded runs list
function listbox2_Callback(hObject, eventdata, handles)

% Update line import number to new selected line
handles.importnr = get(hObject,'Value');

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes during object creation, after setting all properties.
% Loaded runs list
function listbox2_CreateFcn(hObject, eventdata, handles)

% Set background colour to white
if ispc && isequal(get(hObject,'BackgroundColor'), ...
                   get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% Fill list with example text.
gug(1,1) = cellstr('Load output-file');
gug(2,1) = cellstr('to populate list.');
set(hObject,'String',gug)

% Initiate import number variable
handles.importnr = 1;

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% --- Executes on button press in pushbutton7. 
% Load run list line data button
function pushbutton7_Callback(hObject, eventdata, handles)

% Load data into tmp variable with import_n_format subroutine
tmpdat = import_n_format(handles.filedata, handles.hdlines(handles.importnr)); 

% Split loaded data into two tmp matrices.
[tmp1, tmp2] = split_indata(tmpdat);

% make sure imported data is within allowed values
tmp3 = ones(5,1);
tmp3(1) = floor(tmp2(5));
tmp3(2) = tmp2(2);
tmp3(3) = tmp2(3);
tmp3(4) = tmp2(4);
tmp3(5) = floor(handles.calc_settings(5));

%Fill empty gometry data field with zeros
tmp4 = zeros(9,9);
    for i = 1:1:9
        for k = 1:1:9 
        if k <= length(tmp1(1,:))   
            tmp4(i,k) = tmp1(i,k);
        end  
        end  
    end

% Extract old run prefix and format    
p_tmp = handles.filedata(handles.hdlines(handles.importnr));    
p_tmp = strrep(p_tmp,'Date and time of run: ','');
[~ , p_tmp]=strtok(p_tmp);
[~ , p_tmp]=strtok(p_tmp);
p_tmp = char(p_tmp);
p_tmp = p_tmp(2:end);

% Copy data to tables
set(handles.uitable2 , 'data' , tmp3);
set(handles.uitable1 , 'data' , tmp4);
set(handles.edit2,'String',p_tmp);

%Copy table data to variables
handles.calc_settings = get(handles.uitable2 , 'data');
handles.geom_data     = get(handles.uitable1 , 'data');

%Update, save and exit
guidata(hObject, handles);

%-----------------------------------------------------------------------
% Prefix field update function
function edit2_Callback(hObject, eventdata, handles)

% Update String contents on change

%-----------------------------------------------------------------------
% --- Executes during object creation, after setting all properties.
% Prefix field creation
function edit2_CreateFcn(hObject, eventdata, handles)

% Set background to white
if ispc && isequal(get(hObject,'BackgroundColor'), ...
                   get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------
% --- Executes on button press in checkbox5.
% Generate plots checkbox
function checkbox5_Callback(hObject, eventdata, handles)

% Update checkbox status on change

%%%%%%%%%%%%%%%%%%%%%%% FILE END %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
